#include <QCoreApplication>
#include <QTextStream>
#include <QStringList>
#include <QDebug>
#include <QHostAddress>
#include <QHostInfo>
#include "sh/shnet.h"
#include <QTimer>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    //QTextStream out(stdout);


    QHostAddress interface;
    QHostAddress multicast;
    quint16 port = 45454;
    QString nodeName = QString("shcc_%1").arg(QHostInfo::localHostName());
    QStringList propertySet;
    QStringList functionCall;
    int exitIn = 1000;

    foreach (QString arg, a.arguments()) {
        int n = arg.indexOf('=');
        QString name = arg.left(n);
        QString value = arg.right(arg.length() - n - 1);

        if (name == "-i" || name == "-interface")
            interface = QHostAddress(value);
        else if (name == "-m" || name == "-multicast")
            multicast = QHostAddress(value);
        else if (name == "-p" || name == "-port")
            port = value.toUInt();
        else if (name == "-n" || name == "-nodename")
            nodeName == value;
        else if (name == "-ps" || name == "-property_set")
            propertySet.append(value);
        else if (name == "-f" || name == "-function_call")
            functionCall.append(value);
        else if (name == "-e" || name == "-exit_in")
            exitIn = value.toInt();
        else
            qWarning() << "ignoring unsupported argument" << name;
    }

    ShNet net;
    if (!net.join(interface, multicast, port, nodeName)) {
        qWarning() << "can't join network";
        return -1;
    }

    foreach (QString property, propertySet)
        net.setProperty(Url(property));

    foreach (QString function, functionCall)
        net.execFunction(Url(function));
    
    QTimer::singleShot(exitIn, &a, SLOT(quit()));

    return a.exec();
}
